package casa.depesos.app.com.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.Bitmap
import android.graphics.PointF
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import casa.depesos.app.com.R
import casa.depesos.app.com.databinding.ActivityCameraCardBinding
import casa.depesos.app.com.utils.Utils
import com.common.base.task.SilentTask
import com.common.base.task.TaskEngine
import com.otaliastudios.cameraview.CameraException
import com.otaliastudios.cameraview.CameraListener
import com.otaliastudios.cameraview.CameraLogger
import com.otaliastudios.cameraview.CameraOptions
import com.otaliastudios.cameraview.PictureResult
import com.otaliastudios.cameraview.controls.Facing
import com.otaliastudios.cameraview.controls.Preview
import java.io.File


class CameraCardActivity : BaseActivity(), View.OnClickListener {

    private var captureTime: Long = 0
    lateinit var binding: ActivityCameraCardBinding

    override fun needPadding(): Boolean {
        return false
    }

    override fun setStatusBar() {
    }

    override fun onCreate(savedInstanceState: Bundle?) {


        super.onCreate(savedInstanceState)

        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )

        // 隐藏状态栏

        // 隐藏状态栏
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions

        binding = ActivityCameraCardBinding.inflate(layoutInflater)
        var bo = intent.getBooleanExtra("front", false);
        if (bo) {
            binding.tv.text = "Foto delantera"
        } else {
            binding.tv.text = "Foto trasera"
        }
        setContentView(binding.root)
        CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE)
        binding.camera.setLifecycleOwner(this)
        binding.camera.addCameraListener(Listener())

        binding.capturePicture.setOnClickListener(this)
        binding.toggleCamera.setOnClickListener(this)
        binding.close.setOnClickListener { finish() }
    }

    private fun message(content: String, important: Boolean) {
    }

    private inner class Listener : CameraListener() {
        override fun onCameraOpened(options: CameraOptions) {
        }

        override fun onCameraError(exception: CameraException) {
            super.onCameraError(exception)
            message("Got CameraException #" + exception.reason, true)
        }

        override fun onPictureTaken(result: PictureResult) {
            super.onPictureTaken(result)
            if (binding.camera.isTakingVideo) {
                message("Captured while taking video. Size=" + result.size, false)
                return
            }

            // This can happen if picture was taken with a gesture.
            val callbackTime = System.currentTimeMillis()
            if (captureTime == 0L) captureTime = callbackTime - 300
            if (true) {
                try {
                    result.toBitmap(2000, 2000) { bitmap -> showCameraLensRectBitmap(bitmap) }
                } catch (e: UnsupportedOperationException) {
                    Toast.makeText(
                        this@CameraCardActivity,
                        "Can't preview this format: " + result.format,
                        Toast.LENGTH_LONG
                    ).show()
                }
                return
            }
//            PicturePreviewActivity.pictureResult = result
//            val intent = Intent(this@CameraCardActivity, PicturePreviewActivity::class.java)
//            intent.putExtra("delay", callbackTime - captureTime)
//            startActivity(intent)
//            captureTime = 0
//            LOG.w("onPictureTaken called! Launched activity.")
        }

        override fun onExposureCorrectionChanged(
            newValue: Float,
            bounds: FloatArray,
            fingers: Array<PointF>?
        ) {
            super.onExposureCorrectionChanged(newValue, bounds, fingers)
            message("Exposure correction:$newValue", false)
        }

        override fun onZoomChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
            super.onZoomChanged(newValue, bounds, fingers)
            message("Zoom:$newValue", false)
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.capturePicture -> capturePictureSnapshot()
            R.id.toggleCamera -> toggleCamera()
        }
    }

    private fun capturePictureSnapshot() {
        if (binding.camera.isTakingPicture) return
        if (binding.camera.preview != Preview.GL_SURFACE) return run {
            message("Picture snapshots are only allowed with the GL_SURFACE preview.", true)
        }
        captureTime = System.currentTimeMillis()
        message("Capturing picture snapshot...", false)
        binding.camera.takePictureSnapshot()
    }

    private fun toggleCamera() {
        if (binding.camera.isTakingPicture || binding.camera.isTakingVideo) return
        when (binding.camera.toggleFacing()) {
            Facing.BACK -> message("Switched to back camera!", false)
            Facing.FRONT -> message("Switched to front camera!", false)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val valid = grantResults.all { it == PERMISSION_GRANTED }
        if (valid && !binding.camera.isOpened) {
            binding.camera.open()
        }
    }

    private fun showCameraLensRectBitmap(bm: Bitmap?) {
        TaskEngine.getInstance().submit(object : SilentTask("") {
            @Throws(Exception::class)
            override fun runInBackground() {
                val tmp =
                    File(
                        getExternalFilesDir(null),
                        System.currentTimeMillis().toString() + "big.jpg"
                    )
                Utils.saveImageTo(bm, tmp.absolutePath)

                var bitmap = binding.cameraLensView.cropCameraLensRectBitmap(bm, true)
                val destFile =
                    File(
                        getExternalFilesDir(null),
                        System.currentTimeMillis().toString() + "small.jpg"
                    )
                var bo = Utils.saveImageTo(bitmap, destFile.absolutePath)
                h.post {
                    if (bo) {
                        val intent = Intent()
                        intent.putExtras(getIntent())
                        intent.putExtra("path", destFile.absolutePath)
                        setResult(Activity.RESULT_OK, intent)
                        finish()
                    } else {
                        Toast.makeText(
                            this@CameraCardActivity,
                            "Error while writing file.",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        })
    }
}
